const db = require('../db/index');
require('dotenv').config({ path: '.env' })


//添加任务
exports.addTask = (req, res) => {

    let principalName;
    if(req.user.nickname){
        principalName = req.user.nickname
    }else {
        principalName = req.user.username
    }

    const taskInfo = {
        ...req.body,
        releaseTime: new Date(),
        principal: principalName,
        principal_id: req.user.user_id,
        status: 0,
        phone: req.user.phone
    }

    const sql = `INSERT into task set ?;`;
    db.query(sql, taskInfo, (err, results) => {
        //执行SQL语句失败
        if (err) return res.cc(err);
        //执行SQL语句成功，但是获取到的数据条数不等于1
        if (results.affectedRows !== 1) return res.cc('修改失败！');

        res.cc("新添任务成功！", 0)
    })
}

//查询任务
exports.getAllTask = (req,res)=>{
    const sql =`select * from task;`;
    db.query(sql, (err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取失败！');

        res.send({
            status: 0,
            mesage: "获取任务列表成功!",
            retdata: results
        })
    })
}

//查询发布的任务
exports.getMyReleaseTask = (req,res)=>{
    const sql =`select * from task where principal_id = ?;`;
    db.query(sql, req.body.principal_id,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取发布的任务失败！');

        res.send({
            status: 0,
            mesage: "获取发布的任务成功!",
            retdata: results
        })
    })
}

//查询接受的任务
exports.getMyAcceptTask = (req,res)=>{
    const sql =`select * from task where recipient_id = ?;`;
    db.query(sql, req.body.recipient_id,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取接受的任务失败！');

        res.send({
            status: 0,
            mesage: "获取接受的任务成功!",
            retdata: results
        })
    })
}

//查询已完成的任务
exports.getMyDoneTask = (req,res)=>{
    const sql =`select * from task where recipient_id = ? and status = "2";`;
    db.query(sql, req.body.recipient_id,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取已完成的任务失败！');

        res.send({
            status: 0,
            mesage: "获取已完成的任务成功!",
            retdata: results
        })
    })
}

//更新任务信息
exports.updateTask = (req, res) => {
    const sql = `UPDATE task SET ? WHERE task_id = ?;`
    db.query(sql, [req.body, req.body.task_id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('修改任务信息失败！')

        res.cc('修改任务信息成功!', 0)
    })
}

//删除任务
exports.deleteTask = (req,res) => {
    const sql = `DELETE FROM task WHERE task_id = ?;`
    db.query(sql, req.body.task_id, (err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows != 1) return res.cc('删除任务失败！')

        res.cc("删除任务成功！",0)
    })
}